package com.dd.ms.auth.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.dd.ms.auth.api.UserInfoService;
import com.dd.ms.auth.pojo.resp.ApiKeyGeneResponse;
import com.dd.ms.auth.service.ApiKeyService;
import com.dd.ms.auth.vo.UserVO;
import com.dd.ms.common.response.ApiResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/7/23 18:18
 * @Description 用户信息提供
 */
@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Api(tags = "用户信息提供 & API密钥生成与获取")
public class UserInfoController {

    private final UserInfoService userInfoService;
    private final ApiKeyService apiKeyService;

    // 标记资源：资源名为 "getOrder"，配置降级和熔断的处理逻辑
    @SentinelResource(
            value = "UserInfoServiceImpl#getUserInfoByToken",  // 资源名称（在控制台显示，需唯一）
            fallback = "getOrderFallback",  // 降级/熔断时的兜底方法（处理业务异常）
            blockHandler = "getOrderBlockHandler"  // 限流/熔断触发时的阻塞处理（处理 BlockException）
    )
    @PostMapping("/info")
    @ApiOperation("根据token获取用户信息（前端查询后端默认携带权限信息）")
    public ApiResponse<UserVO> userInfo(@RequestHeader("Authorization") String token) {
        log.info("token = " + token);
        String tokenStr = token.split(" ")[1]; // 去除 Bearer
        return ApiResponse.success(userInfoService.getUserInfoByToken(tokenStr, true));
    }

    // 降级兜底方法：参数和返回值必须与原方法一致
    public ApiResponse<UserVO> getUserInfoFallback(String token, Throwable e) {
        log.warn("用户信息服务降级，token: {}, 原因: {}", token, e.getMessage());
        return ApiResponse.error("用户服务暂时不可用，请稍后重试");
    }

    // 阻塞处理方法：参数必须与原方法一致，最后加 BlockException
    public ApiResponse<UserVO> getUserInfoBlockHandler(String token, BlockException e) {
        log.warn("用户信息服务限流，token: {}, 规则: {}", token, e.getRule());
        return ApiResponse.error("系统繁忙，请稍后再试");
    }

    @PostMapping("/gene-api-key")
    @ApiOperation("生成三方API签名认证访问密钥、秘密密钥并返回（已经存在则进行更新并返回）")
    public ApiResponse<ApiKeyGeneResponse> geneApiKey(@RequestHeader("Authorization") String token) {
        log.info("token = " + token);
        String tokenStr = token.split(" ")[1]; // 去除 Bearer
        return ApiResponse.success(apiKeyService.geneApiKey(tokenStr));
    }

    @PostMapping("/info/apiKeys")
    @ApiOperation("根据token获取用户apiKeys")
    public ApiResponse<String> apiKeys(@RequestHeader("Authorization") String token) {
        log.info("token = " + token);
        return ApiResponse.success(userInfoService.getUserApiKeyByToken(token));
    }
}
